package com.wslds.blog.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.im4java.process.ProcessStarter;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wslds.base.dao.BaseDaoImpl;
import com.wslds.base.util.BlogCons;
import com.wslds.base.util.SessionUtil;
import com.wslds.bean.Tag;
import com.wslds.bean.Type;
import com.wslds.bean.ext.TaginstExt;

public class ServletContextLoaderListener implements ServletContextListener
{

	public void contextDestroyed(ServletContextEvent arg0)
	{

	}

	public void contextInitialized(ServletContextEvent arg0)
	{
		ServletContext cnx = arg0.getServletContext();
		SessionUtil.setServletContext(cnx);	//把ServletContext放到 SessionUtil里
		cnx.setAttribute("contextPath", cnx.getContextPath());
	
		
		ProcessStarter.setGlobalSearchPath("D:\\Program Files\\ImageMagick-6.6.6-Q16");
		
		
		BaseDaoImpl dao = (BaseDaoImpl)WebApplicationContextUtils.getWebApplicationContext(cnx).getBean("iDao");
		
		//把标签MAP放到全局
		TaginstExt tagParam = new TaginstExt();
		List<TaginstExt> taginstExt = dao.findExt("tag_select_ext", tagParam);
		Map<Long,List<TaginstExt>> taginstMap = new HashMap<Long,List<TaginstExt>>();
		for( TaginstExt taginst: taginstExt ){
			if( taginstMap.containsKey(taginst.getArtId()) ){
				List<TaginstExt> list = taginstMap.get(taginst.getArtId());
				list.add(taginst);
			}else{
				List<TaginstExt> list = new ArrayList<TaginstExt>();
				list.add(taginst);
				taginstMap.put(taginst.getArtId(), list);
			}
		}
		cnx.setAttribute(BlogCons.APPLICATION.TAGINST, taginstMap);
		
		//把类型放到全局
		Type typeParam = new Type();
		List<Type> typeList = dao.find("type", typeParam);
		Map<Long,Type> typeMap = new HashMap<Long,Type>();
		for( Type type: typeList ){
			typeMap.put(type.getId(), type);
		}
		cnx.setAttribute(BlogCons.APPLICATION.TYPE, typeMap);
		
		//把标签放到全局
		List<Tag> tagList = dao.find("tag", null);
		Map<Long,String> tagMap = new HashMap<Long,String>();
		for( Tag tag: tagList ){
			tagMap.put(tag.getId(), tag.getName());
		}
		cnx.setAttribute(BlogCons.APPLICATION.TAG, tagMap);
		
		
		//侧边栏全局数据
		cnx.setAttribute("typeList", dao.findExt("type_select_sidebar", null));
		cnx.setAttribute("dateList", dao.findExt("date_select_sidebar", null));
		
	}

}
